def main():
	import Image
	im = Image.open('zigzag.gif')

	p = im.getpalette()
	for i in range(0, len(p), 3):
		assert p[i] == p[i+1] == p[i+2] # R==G==B in each palette color
	p2rgb = p[::3] # maps palette index to its R value
	assert len(set(p2rgb)) == 256 # all R values appear in palette
	assert len(im.getcolors()) == 256 # all palette colors are used

	# >>> pdata = im.getdata()
	# >>> for i in range(10):
	# ...     p = pdata[i]
	# ...     print "%3d %3d" % (p, p2rgb[p])

	pdata = im.getdata()
	exceptions = []
	expected = None
	indices = []
	for i, p in enumerate(pdata):
		if expected is not None and p != expected:
			exceptions.append(p)
			indices.append(i)
		expected = p2rgb[p]

	bzdata = "".join(map(chr, exceptions))
	import bz2
	bzexpanded = bz2.decompress(bzdata)

	im2 = Image.new("RGB", im.size)
	colors = [(255, 255, 255)] * len(pdata)
	blue = 0, 0, 255
	for i in indices:
		colors[i] = blue
	im2.putdata(colors)
	im2.save(open('output.jpg', 'w'))
	im2.show()

	allwords = bzexpanded.split()
	import keyword
	oddballs = set(allwords) - set(keyword.kwlist)
	
	for word in allwords:
		if word in oddballs:
			print word
			oddballs.remove(word)
			if not oddballs:
				break
	# ../ring/bell.html
	# repeat
	# switch
	
if __name__ == '__main__':
	main()
